/* eslint-disable no-param-reassign */
import numbro from 'numbro';
import zh from 'numbro/languages/zh-CN';
numbro.registerLanguage(zh);
numbro.setLanguage('en');

export const formatNumber = (n) => {
  try {
    return numbro(+n)
      .format({
        average: true,
        mantissa: 2,
        trimMantissa: true,
        roundingFunction: (n) => n,
      })
      .toUpperCase();
  } catch (e) {
    return 'NaN';
  }
};

// 下面这个要被淘汰，因为传入字符串小数就挂了
export const formatNumberThousand = (n) =>
  `${+n}`.replace(/\d{1,3}(?=(\d{3})+$)/g, (s) => `${s},`);

export const fmtNumberThousand = (n, mantissa = 2) => {
  try {
    return numbro(+n)
      .format({
        thousandSeparated: true,
        mantissa,
      })
      .toUpperCase();
  } catch (e) {
    return 'NaN';
  }
};

//对整数或浮点数做出不同的格式化
export const formatIntFloatNumber = (obj) => {
  obj = +obj;
  if (typeof obj === 'number' && obj % 1 === 0)
    return formatNumberThousand(obj);
  else return fmtNumberThousand(obj);
};

export const formatPercent = (n, mantissa) => {
  try {
    return numbro(+n).format({
      output: 'percent',
      mantissa: isNaN(+mantissa) ? 2 : mantissa,
    });
  } catch (e) {
    return 'NaN';
  }
};

//对整数或百分比做出不同的格式化
export const formatNumberOrPercent = (obj) => {
  obj = +obj;
  if (typeof obj === 'number' && obj % 1 === 0)
    return formatNumberThousand(obj);
  else return formatPercent(obj);
};

export const upDown = (n) => (+n > 0 ? 'up' : 'down');

export const formatCurrency = (n) => {
  if (n === undefined || n === '') return 'NaN';
  numbro.setLanguage('zh-CN');
  const res = numbro(n).formatCurrency({
    thousandSeparated: true,
    mantissa: 2,
  });
  numbro.setLanguage('en');
  return res;
};

export const numberWithThousands = (x) => {
  if (typeof x !== 'number') return x;
  return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
};

// 给后端的置信度数据必须是整数并*100
export const processConfidenceNumber = (number) => {
  const result = Math.round(number * 100);
  if (!Number.isNaN(result)) {
    return Math.round(number * 100);
  }
  throw new Error('error param');
};

//将比例数据*100后，并保留三位小数,返回为Number类型
export const formatFloatThree = (n) => {
  return Number((Number(n) * 100).toFixed(3));
};

export const formatByte = (n) => {
  try {
    return numbro(+n).format({
      output: 'byte',
      base: 'binary',
      mantissa: 2
    });
  } catch (e) {
    return 'NaN';
  }
};
